package org.hbkj.springbootmybatis.service;

import org.hbkj.springbootmybatis.dao.OrderDao;
import org.hbkj.springbootmybatis.entity.OrderDo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OrderService {

    private final OrderDao orderDao;

    public OrderService(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    // 创建订单 - 完善业务逻辑
    @Transactional
    public int createOrder(OrderDo order) {
        // 参数校验
        if (order.getUserId() == null || order.getUserId() <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        if (order.getGoodsId() == null || order.getGoodsId() <= 0) {
            throw new IllegalArgumentException("商品ID不能为空且必须大于0");
        }
        if (order.getQuantity() == null || order.getQuantity() <= 0) {
            throw new IllegalArgumentException("购买数量必须大于0");
        }

        // 设置默认值
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        // 确保订单状态有初始值
        if (order.getOrderStatus() == null) {
            order.setOrderStatus("待付款");
        }

        // 计算总价（假设单价已在前端或其他服务计算好传入）
        if (order.getUnitPrice() != null && order.getQuantity() != null) {
            BigDecimal totalPrice = order.getUnitPrice()
                    .multiply(BigDecimal.valueOf(order.getQuantity()));
            order.setTotalPrice(totalPrice);
        }

        return orderDao.insertOrder(order);
    }

    // 根据用户ID查询订单（返回空列表而非null）
    public List<OrderDo> getOrdersByUserId(Integer userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        return Optional.ofNullable(orderDao.selectOrdersByUserId(userId))
                .orElse(List.of());
    }

    // 查询所有订单
    public List<OrderDo> getAllOrders() {
        return orderDao.selectAllOrders();
    }

    // 更新订单状态 - 增加参数校验和状态流转逻辑
    public int updateOrderStatus(String orderId, String orderStatus) {
        if (orderId == null || orderStatus == null) {
            throw new IllegalArgumentException("订单ID和订单状态不能为空");
        }

        // 可以添加状态流转校验，防止非法状态变更
        // 例如：已完成的订单不能再变为待付款
        // 这里简化处理，实际项目中可能需要更复杂的状态机逻辑

        return orderDao.updateOrderStatus(orderId, orderStatus, new Date());
    }

    // 删除订单 - 增加业务校验
    public int deleteOrder(String orderId) {
        if (orderId == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        // 检查订单状态，通常只有待付款状态可以删除
        Optional<OrderDo> orderOptional = getOrderById(orderId);
        if (orderOptional.isPresent()) {
            OrderDo order = orderOptional.get();
            if (!"待付款".equals(order.getOrderStatus())) {
                throw new IllegalStateException("只有待付款状态的订单可以删除");
            }
        } else {
            throw new IllegalArgumentException("订单不存在");
        }

        return orderDao.deleteOrder(orderId);
    }

    // 根据订单ID查询（返回Optional防止空指针）
    public Optional<OrderDo> getOrderById(String orderId) {
        if (orderId == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        return Optional.ofNullable(orderDao.selectByOrderId(orderId));
    }

    // 统计用户订单数量
    public int countOrdersByUserId(Integer userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        return orderDao.countByUserId(userId);
    }

    // 根据状态查询订单
    public List<OrderDo> getOrdersByStatus(String orderStatus) {
        if (orderStatus == null) {
            throw new IllegalArgumentException("订单状态不能为空");
        }
        return orderDao.selectByStatus(orderStatus);
    }
}